Loop Over Array of Objects and Combine them if they have similar keys

60

//Convert This
var array = [
   {id=1, name = "Orange"},
   {id=1, name = "Blue"},
   {id=1, name = "Green"},
   {id=2, name = "Blue"},
   {id=3, name = "Orange"},
   {id=3, name = "Blue"}
]

//to this
var newArray = [
   {id=1, nameList = [Orange, Blue, Green]},
   {id=2, nameList = [Blue]},
   {id=3, namelist = [Orange, Blue]}
]

var array = [   {id:1, name : "Orange"},   {id:1, name : "Blue"},   {id:1, name : "Green"},   {id:2, name : "Blue"},   {id:3, name : "Orange"},   {id:3, name : "Blue"}]

var result = Object.values(array.reduce((a, c) => {
  (a[c.id] || (a[c.id] = {id: c.id, nameList: []})).nameList.push(c.name);
  return a;
}, {}));

console.log(result);

Comments

Submit
0 Comments